/**
 * Copyright 2011, Under-Ground Studio.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.zju.vlis.aus.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import cn.edu.zju.vlis.aus.MainActivity;
import cn.edu.zju.vlis.aus.R;
import cn.edu.zju.vlis.aus.bean.UsageRecord;
import cn.edu.zju.vlis.aus.db.UsageRecordDAO;
import cn.edu.zju.vlis.aus.util.AppHelper;
import cn.edu.zju.vlis.aus.util.IconCache;
import cn.edu.zju.vlis.aus.util.IconCache.LoadSingleIconTask;

public class UnusedActivity extends ListActivity implements OnItemClickListener {
	private static final int DIALOG_ID_CONFIRM = 1;
	private static final int MENU_ITEM_LAUNCH = 0;
	private static final int MENU_ITEM_UNINSTALL = 1;
	private static final int MENU_ITEM_FILTER = 2;

	private List<UsageRecord> unusedList;
	private String packageName;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// set empty view
		LayoutInflater inflater = LayoutInflater.from(this);
		View emptyView = inflater
				.inflate(R.layout.list_empty_view_unused, null);
		emptyView.setVisibility(View.GONE);
		((ViewGroup) getListView().getParent()).addView(emptyView);
		getListView().setEmptyView(emptyView);
		// set adapter
		createUnusedList();
		setListAdapter(new UnusedListAdapter());
		// set listener
		getListView().setOnItemClickListener(this);
		// context menu
		registerForContextMenu(getListView());
	}

	private void createUnusedList() {
		UsageRecordDAO dao = new UsageRecordDAO(this);
		unusedList = dao.getUnusedList();
		dao.close();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		UsageRecord rec = (UsageRecord) getListAdapter().getItem(position);
		if (rec != null) {
			packageName = rec.getPackageName();
			showDialog(DIALOG_ID_CONFIRM);
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_ID_CONFIRM:
			return new AlertDialog.Builder(UnusedActivity.this)
					.setTitle(R.string.launch_confirm_dialog_title)
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(R.string.launch_confirm_dialog_msg)
					.setPositiveButton(android.R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									boolean success = AppHelper
											.launchApplication(
													UnusedActivity.this,
													packageName);
									if (!success) {
										refresh();
									}
								}
							})
					.setNegativeButton(android.R.string.cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {

								}
							}).create();
		}
		return super.onCreateDialog(id);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		menu.add(Menu.NONE, MENU_ITEM_LAUNCH, 0, R.string.menu_item_launch);
		menu.add(Menu.NONE, MENU_ITEM_UNINSTALL, 1,
				R.string.menu_item_uninstall);
		menu.add(Menu.NONE, MENU_ITEM_FILTER, 2, R.string.menu_item_filter);
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		UsageRecord rec = (UsageRecord) getListAdapter().getItem(
				info.position );
		if (rec != null) {
			String packageName = rec.getPackageName();
			switch (item.getItemId()) {
			case MENU_ITEM_LAUNCH:
				boolean success = AppHelper
						.launchApplication(this, packageName);
				if (!success) {
					refresh();
				}
				break;
			case MENU_ITEM_UNINSTALL:
				AppHelper.uninstallApp(UnusedActivity.this, packageName);
				// refresh will be called by the MainActivity.onStart()
				break;
			case MENU_ITEM_FILTER:
				rec.setStatistic(false);
				ArrayList<UsageRecord> list = new ArrayList<UsageRecord>();
				list.add(rec);
				UsageRecordDAO dao = new UsageRecordDAO(this);
				dao.updateStatistic(list);
				dao.close();
				MainActivity main = (MainActivity) getParent();
				main.refreshForAppFilter();
				break;
			}
		}
		return super.onContextItemSelected(item);
	}

	public void refresh() {
		UnusedListAdapter adapter = (UnusedListAdapter) getListAdapter();
		if (adapter != null) {
			createUnusedList();
			adapter.notifyDataSetChanged();
		}
	}

	public void setTitleWithCount() {
		String title = getResources().getString(R.string.title_never_used);
		if (unusedList != null) {
			int count = unusedList.size();
			StringBuffer titleBuilder = new StringBuffer(title);
			titleBuilder.append('(');
			titleBuilder.append(count);
			titleBuilder.append(')');
			title = titleBuilder.toString();
		}
		MainActivity parent = (MainActivity) getParent();
		parent.setTitle(title);
	}

	private class UnusedListAdapter extends BaseAdapter {
		private LayoutInflater inflater;

		public UnusedListAdapter() {
			inflater = LayoutInflater.from(UnusedActivity.this);
		}

		@Override
		public int getCount() {
			if (unusedList != null) {
				return unusedList.size();
			} else {
				return 0;
			}
		}

		@Override
		public Object getItem(int position) {
			if (unusedList != null) {
				return unusedList.get(position);
			} else {
				return null;
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v;
			if (convertView == null) {
				v = inflater.inflate(R.layout.list_item_never_used, null);
				ViewHolder vh = new ViewHolder();
				vh.iconView = (ImageView) v
						.findViewById(R.id.image_app_icon_unused);
				vh.appNameView = (TextView) v
						.findViewById(R.id.text_app_name_unused);
				vh.btn = (Button) v.findViewById(R.id.btn_uninstall);
				v.setTag(vh);
			} else {
				v = convertView;
			}
			ViewHolder vh = (ViewHolder) v.getTag();
			UsageRecord rec = (UsageRecord) getItem(position);
			// set icon
			Drawable icon = IconCache.getIcon(rec.getPackageName());
			if (icon == null) {
				icon = IconCache.getDefaultIcon();
				new LoadSingleIconTask(UnusedActivity.this,
						rec.getPackageName(), vh.iconView).execute();
			}
			vh.iconView.setImageDrawable(icon);
			// set the app name
			vh.appNameView.setText(rec.getAppName());
			vh.btn.setText(R.string.btn_uninstall);
			vh.btn.setTag(rec.getPackageName());// set for the onClick
			vh.btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String packageName = (String) v.getTag();
					AppHelper.uninstallApp(UnusedActivity.this, packageName);
				}
			});
			return v;
		}

		private class ViewHolder {
			private ImageView iconView;
			private TextView appNameView;
			private Button btn;
		}
	}

}
